<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;">
      <div class="title">{{$t('achievements.title1')}}</div>
      <div class="menu-search">
        <div class="menu-title">
          <!-- 修改时间 -->
          <div class='searchItem searchItem-date'>
            <span>{{$t('sms.uptTime')}}</span>
            <el-date-picker
              size='small'
              v-model="listQuery.crtTimeBegine"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('rule.beginDate')">
            </el-date-picker>
            <b>{{$t('approval.go')}}</b>
            <el-date-picker
              size='small'
              v-model="listQuery.crtTimeEnd"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('rule.endDate')">
            </el-date-picker>
          </div>
          <!-- 操作人 -->
          <div class='searchItem'>
            <span>{{$t('sms.workUser')}}</span>
            <el-input v-model='listQuery.workUser' placeholder="" size='small'></el-input>
          </div>
          <div class="menu-title-btn" style="margin-left: 20px;">
            <button type="button" @click="search">{{$t('btn.query')}}</button>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between;">
        <div class="title">{{$t('DailyStatistics.ListDetails')}}</div>
        <div>
          <el-button
            type="primary"
            @click="handleAddSmsTemplate"
            size="small">{{$t('sms.addTemplate')}}</el-button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 5px;"
        border
        size="mini"
      >
        <el-table-column :label="$t('user.num')" header-align="center" align="center" width="60">
          <template slot-scope="scope">
            <span>{{scope.row.index}}</span>
          </template>
        </el-table-column>
        <!-- 短信内容 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="smsContent"
          :label="$t('sms.smsContent')"
        ></el-table-column>
        <!-- 短信说明 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="smsXplain"
          width="160"
          :label="$t('sms.smsXplain')"
        ></el-table-column>
        <!-- 修改时间 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="uptTime"
          width="160"
          :label="$t('sms.uptTime')"
        ></el-table-column>
        <!-- 操作人 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="workUser"
          width="160"
          :label="$t('sms.workUser')"
        ></el-table-column>
        <el-table-column align="center" header-align="center"  :label="$t('user.operation')" width="160">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="handleEdit(scope.row)" >{{$t('btn.edit')}}</el-button>
            <el-button size="small" type="text" @click="handleSend(scope.row)">{{$t('sms.send')}}</el-button>
            <el-button size="small" type="text" @click="handleRemove(scope.row)">{{$t('sms.del')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[5, 10, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 短信模板对话框 -->
    <el-dialog
      :title="textMap[dialogStatus2]"
      :visible.sync="dialogFormVisible2"
      :before-close="closeDialog"
    >
      <el-form
        :model="form" 
        :rules="rules" 
        ref="form" 
        label-position="top"
        label-width="100px"
        style="width:85%;margin-left:5%"
      >
        <el-form-item :label="$t('sms.smsXplain')" prop="smsXplain">
              <el-input size="small" v-model="form.smsXplain" placeholder=""></el-input>
            </el-form-item>
        <div style="position:relative;">
          <el-popover
            placement="right"
            :title="$t('sms.tooltipTitle')"
            width="250"
            trigger="click">
            <div>
              <ul style="list-style:none;padding:0;">
                <li>{{$t('sms.appName')}}: [Nama Aplikasi]</li>
                <li>{{$t('sms.verifyCode')}}: (kode Verifikasi)</li>
                <li>{{$t('sms.orderId')}}: [order number]</li>
                <li>{{$t('sms.deadDate')}}: [Repayment date]</li>
                <li>{{$t('sms.fromDueDate')}}: [From the due date]</li>
                <li>{{$t('sms.dueDay')}}: [Overdue days]</li>
              </ul>
              <!-- App名称：[Nama Aplikasi]<br/>验证码：(kode Verifikasi)<br/>订单号：[order number]<br/>到期日期：[Repayment date]<br/>距到期日：[From the due date]<br/>逾期天数：[Overdue days] -->
            </div>
            <a style="font-size:12px;color:#cc3333;position:absolute;top:10px;left:70px;" slot="reference">{{$t('sms.viewToolTip')}}</a>
          </el-popover>
          <el-form-item :label="$t('sms.smsContent')" prop="smsContent">
            <el-input type="textarea" v-model="form.smsContent" :autosize="{ minRows: 4, maxRows: 7}" placeholder=""></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button v-if="dialogStatus2=='create'" type="primary" :loading="submitBtnLoading" @click="submitCreateForm('form')">{{$t('btn.conserve')}}</el-button>
        <el-button v-else type="primary" @click="submitUpdateForm('form')">{{$t('btn.conserve')}}</el-button>
      </div>
    </el-dialog>
    <!--发送对话框-->
    <el-dialog
      :title="textMap[dialogStatus1]"
      :visible.sync="dialogFormVisible1"
      width="40%"
      :before-close="closeUploadDialog"
    >
     <el-upload ref="upload"
      action="string"
      :multiple="false"
      :http-request="uploadFile"
      :auto-upload="false"
      :limit="1"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      > 
      <span style="float:left;line-height:32px;">{{$t('sms.selectTo')}}</span>
      <el-button style="margin-left:10px;" slot="trigger" size="small" type="primary">{{$t('sms.importExcel')}}<i class="el-icon-upload el-icon--right"></i></el-button>
      <el-button style="margin-left:10px;" type="primary" size="small" @click="download">{{$t('sms.download')}}</el-button>
      <div slot="tip" class="el-upload__tip">{{$t('sms.uploadTooltip')}}</div>
      </el-upload> 
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="success" :loading="submitBtnLoading" @click="send" icon="el-icon-s-promotion">{{$t('sms.confirmSend')}}</el-button>      
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { padLeftZero } from 'utils/index'
import { smsTemplatePage, addSmsTemplate, delSmsTemplate, groupSendSms } from 'api/duanxin/index'
export default {
  data() {
    return {
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,
        page: 1,
        // 修改时间
        crtTimeBegine: '',
        crtTimeEnd: '',
        // 操作人
        workUser: '',
        // //1.短信模板分页  2.短信群发配置
        smsTemplateType: '2'
      },
      tableData: [],
      dialogStatus1: '',
      dialogStatus2: '',
      // 短信模板对话框显示状态
      dialogFormVisible1: false,
      // 发送模板对话框显示状态
      dialogFormVisible2: false,
      submitBtnLoading: false,
      currentId: null,
      textMap: {
        update: this.$t('btn.edit'),
        create: this.$t('btn.create'),
        send: '发送'
      },
      // 短信模板表单数据
      form: {
        id: '',
        // 短信模板标题\短信说明
        smsXplain: '',
        // 短信模板类型
        smsType: '',
        // 逾期天数前/距离还款日前（几天）
        smsDays: '',
        // 短信内容
        smsContent: '',
        // 添加1 修改2
        addOrUpdate: '',
        // 1.短信模板添加模板  2.短信群发配置添加模板
        smsTemplateType: '2'
      },
      rules: {
        smsXplain: [{
          required: true,
          message: this.$t('sms.smsXplainRequired')
        }],
        smsType: [{
          required: true,
          message: this.$t('sms.smsTypeRequired')
        }],
        smsDays: [{
          required: true,
          message: this.$t('sms.smsDaysRequired')
        }, {
          type: 'number', message: this.$t('sms.smsDaysNumber')
        }],
        smsContent: [{
          required: true,
          message: this.$t('sms.smsContentRequired')
        }, {
          max: 1000,
          message: this.$t('sms.smsContentLess1000'),
          trigger: 'blur'
        }]
      }
    };
  },
  computed: {
    ...mapGetters(['elements', ''])
  },
  created() {
    // if (this.MessagePushPage.has(this.$route.path)) {
    //   this.listQuery = this.MessagePushPage.get(this.$route.path);
    // }
    this.initDate()
    this.getList();
  },
  methods: {
    GetDateStr(AddDayCount) {
      const dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount);// 获取AddDayCount天后的日期
      const y = dd.getFullYear();
      const m = padLeftZero(dd.getMonth() + 1, 2);
      const d = padLeftZero(dd.getDate(), 2);
      return y + '-' + m + '-' + d;
    },
    initDate() {
      this.listQuery.crtTimeBegine = this.GetDateStr(0)
      this.listQuery.crtTimeEnd = this.GetDateStr(0)
    },
    // 添加短信模板
    handleAddSmsTemplate() {
      this.dialogStatus2 = 'create'
      this.dialogFormVisible2 = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.form = Object.assign(this.form, row)
      // console.log(this.form)
    },
    // 上传
    uploadFile(item) {
      const form = new FormData()
      form.append('id', this.currentId)
      form.append('excel', item.file)
      this.submitBtnLoading = true
      groupSendSms(form).then(res => {
        this.submitBtnLoading = false
        if (res.status === 200) {
          this.getList()
          this.$refs.upload.clearFiles()
          this.dialogFormVisible1 = false
          this.$notify({
            title: this.$t('user.success'),
            message: this.$t('approvalDispatch.opersuccess'),
            type: 'success',
            duration: 2000
          });
        }
      })
    },
    // 发送
    handleSend(row) {
      this.dialogStatus1 = 'send'
      this.dialogFormVisible1 = true
      this.currentId = row.id
    },
    // 下载短信模板
    download() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/vendor/Export2Excel')
        const tHeader = ['phoneNum'];
        export_json_to_excel(tHeader, [], this.$t('sms.lianxiren'))
      })
    },
    send() {
      this.$refs.upload.submit();
    },
    // 删除
    handleRemove(row) {
      this.$confirm(this.$t('user.cue1'), this.$t('user.cue2'), {
        confirmButtonText: this.$t('btn.confirm'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        delSmsTemplate({ id: row.id }).then(res => {
          if (res.status === 200) {
            this.getList()
            this.$notify({
              title: this.$t('user.success'),
              message: this.$t('user.delsuccess'),
              type: 'success',
              duration: 2000
            });
          }
        })
      })
    },
    // 关闭
    closeDialog(done) {
      done()
      this.resetForm2()
      this.getList()
    },
    closeUploadDialog(done) {
      done()
      this.$refs.upload.clearFiles()
    },
    // 新增
    submitCreateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.addOrUpdate = 1
          this.form.channel = this.listQuery.channel
          this.save()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 更新
    submitUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.addOrUpdate = 2
          // this.form.channel = this.listQuery.channel
          this.save()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 保存
    save() {
      this.submitBtnLoading = true
      addSmsTemplate(this.form).then(res => {
        this.submitBtnLoading = false
        if (res.status === 200) {
          this.resetForm2()
          this.dialogFormVisible2 = false
          this.$notify({
            title: this.$t('groupType.success'),
            message: this.$t('groupType.crtsuccess'),
            type: 'success',
            duration: 2000
          });
          this.getList()
        }
      }).catch(() => {
        this.submitBtnLoading = false
      })
    },
    resetForm2() {
      this.$refs.form.resetFields();
      this.form = {
        id: '',
        // 短信模板标题\短信说明
        smsXplain: '',
        // 短信模板类型
        smsType: '',
        // 逾期天数前/距离还款日前（几天）
        smsDays: '',
        // 短信内容
        smsContent: '',
        // 添加1 修改2
        addOrUpdate: '',
        // 1.短信模板添加模板  2.短信群发配置添加模板
        smsTemplateType: '2'
      }
    },
    getList() {
      // const params = this.listQuery
      this.listLoading = true
      smsTemplatePage(this.listQuery).then(res => {
        this.listLoading = false
        if (res.status === 200) {
          const records = res.data.records
          const total = parseInt(res.data.total)
          records.forEach((item, index) => {
            item.index =
              index + (this.listQuery.page - 1) * this.listQuery.limit + 1;
          })
          this.tableData = records
          this.total = total
        }
      });
    },
    // 查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
</style>